package com.zrwl.poscloud.xo.service.impl;

import com.zrwl.poscloud.xo.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.TemplateEngine;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired(required = false)
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;
    @Override
    public void sendEmail(String from, String to, String subject, String text) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);// 发件人
        simpleMailMessage.setTo(to); // 收件人
        simpleMailMessage.setSubject(subject);// 邮件主题
        simpleMailMessage.setText(text); // 邮件内容
        javaMailSender.send(simpleMailMessage);
    }

    @Override
    public void sendHtmlMail(String to, String subject) throws MessagingException {
        Context context = new Context();
        //设置参数
        context.setVariable("id", "123456");
        //emailTemplate为模板文件的文件名，即html demo的文件名
        String content = templateEngine.process("html", context);//Html为网页文件
        //创建message
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //发件人
        helper.setFrom("1273692478@qq.com");
        //收件人
        helper.setTo(to);
        //邮件标题
        helper.setSubject(subject);
        //true指的是html邮件
        helper.setText(content, true);
        //发送邮件
        javaMailSender.send(message);
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 初始化参数
    private static Properties prop;
    // 发件人
    private static InternetAddress sendMan = null;
    static {
        prop = new Properties();
        prop.put("mail.transport.protocol", "smtp"); // 指定协议
        prop.put("mail.smtp.host", "smtp.qq.com"); // 主机 stmp.qq.com
        // prop.put("mail.smtp.port", 25); // 端口
        prop.put("mail.smtp.auth", "true"); // 用户密码认证
        prop.put("mail.debug", "true"); // 调试模式
        try {
            sendMan = new InternetAddress("1273692478@qq.com");
        } catch (AddressException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public String sendMailWithFile() throws MessagingException {
        // 1. 创建邮件会话
        Session session = Session.getDefaultInstance(prop);
        // 2. 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 3. 设置参数：标题、发件人、收件人、发送时间、内容
        message.setSubject("带图片邮件");
        message.setSender(sendMan);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("2771768682@qq.com"));
        message.setSentDate(new Date());

        /*
         * 带附件(图片)邮件开发
         */
        // 构建一个总的邮件块
        MimeMultipart mixed = new MimeMultipart("mixed");
        // ---> 总邮件快，设置到邮件对象中
        message.setContent(mixed);
        // 左侧： （文本+图片资源）
        MimeBodyPart left = new MimeBodyPart();
        // 右侧： 附件
        MimeBodyPart right = new MimeBodyPart();
        // 设置到总邮件块
        mixed.addBodyPart(left);
        mixed.addBodyPart(right);

        /****** 附件 ********/
        String attr_path = "C:\\xiangmu\\11_message\\src\\main\\resources\\a.docx";//!!!!!!!!!!!!!!!!!!!!!!!
        DataSource attr_ds = new FileDataSource(new File(attr_path));
        DataHandler attr_handler = new DataHandler(attr_ds);
        right.setDataHandler(attr_handler);
        right.setFileName("a.docx");

        /*************** 设置邮件内容: 多功能用户邮件 (related) *******************/
        // 4.1 构建一个多功能邮件块
        MimeMultipart related = new MimeMultipart("related");
        // ----> 设置到总邮件快的左侧中
        left.setContent(related);

        // 4.2 构建多功能邮件块内容 = 左侧文本 + 右侧图片资源
        MimeBodyPart content = new MimeBodyPart();
        MimeBodyPart resource = new MimeBodyPart();

        // 设置具体内容: a.资源(图片)
        String filePath = "C:\\xiangmu\\11_message\\src\\main\\resources\\b.png";//!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        DataSource ds = new FileDataSource(new File(filePath));
        DataHandler handler = new DataHandler(ds);
        resource.setDataHandler(handler);
        resource.setContentID("b.png"); // 设置资源名称，给外键引用

        // 设置页面body： c.测试加页面body里面的内容
        String htmlBody="<p>您好，感谢您的注册，这时一封验证邮件，请点击下面的链接完成注册！</p>\n" +
                "<a href=\"#\" th:href=\"@{http://www.baidu.com(id=${id})}\">点我完成注册</a>";

        // 设置具体内容: b.文本
        content.setContent("测试程序带图片加附件"+
                        "<img src='cid:b.png'/>"
                        +htmlBody
                , "text/html;charset=UTF-8");

        related.addBodyPart(content);
        related.addBodyPart(resource);

        // 5. 发送
        Transport trans = session.getTransport();
        trans.connect("1273692478@qq.com", "krnnjyvpjweibabg");
        trans.sendMessage(message, message.getAllRecipients());
        trans.close();
        return "发送成功";
    }
}
